import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:travel/model/hotel.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/ui/scroll_refresh_config.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

class HotelSearchController extends GetxController {
  late TextEditingController textEditingController;

  RxList<String> tabs = ['综合排序', '最近距离', '星级最高', '价格最便宜'].obs;

  RxInt tabIndex = 0.obs;

  RefreshController refreshController = RefreshController();

  RxList<HotelModel> pageList = RxList([]);

  @override
  void onInit() {
    textEditingController = ToolsUtils.editingController('北海工体中心');
    initData();
    super.onInit();
  }

  @override
  void onClose() {
    refreshController.dispose();
    textEditingController.dispose();
    super.onClose();
  }

  void initData() {
    pageList.add(HotelModel(
        name: '锦江之星风尚酒店(北海三里屯店)',
        address: '北海市海城区东直门外南二里庄29号1幢',
        price: 579,
        area: '海城区',
        imgUrl:
            'https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00002-713.jpg'));
    pageList.add(HotelModel(
        name: '北海万达文华酒店',
        address: '北海市银海区东直门外南二里庄29号1幢',
        price: 399,
        area: '银海区',
        imgUrl:
            'https://img1.baidu.com/it/u=2046807301,2551492904&fm=253&fmt=auto&app=138&f=JPEG?w=888&h=500'));
    pageList.add(HotelModel(
        name: '北海广渠门漫心酒店',
        address: '北海市合浦县东直门外南二里庄29号1幢',
        price: 478,
        area: '合浦县',
        imgUrl:
            'https://img1.baidu.com/it/u=1512264951,2503995626&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=800'));
    pageList.add(HotelModel(
        name: '锦江之星风尚酒店(北海三里屯店)',
        address: '北海市海城区东直门外南二里庄29号1幢',
        price: 389,
        area: '海城区',
        imgUrl:
            'https://img2.baidu.com/it/u=3206337597,3928032791&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'));
    pageList.add(HotelModel(
        name: '北海望京希尔顿欢朋酒店',
        address: '北海市海城区东直门外南二里庄29号1幢',
        price: 189,
        area: '海城区',
        imgUrl:
            'https://img2.baidu.com/it/u=874687570,4272745671&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'));
    pageList.add(HotelModel(
        name: '全季酒店(北海天坛店)',
        address: '北海市海城区东直门外南二里庄29号1幢',
        price: 489,
        area: '海城区',
        imgUrl:
            'https://img2.baidu.com/it/u=1915459,4007195949&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'));
    pageList.add(HotelModel(
        name: '北海望京希尔顿欢朋酒店',
        address: '北海市铁山港区东直门外南二里庄29号1幢',
        price: 289,
        area: '铁山港区',
        imgUrl:
            'https://img2.baidu.com/it/u=1915459,4007195949&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500'));
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 35) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }
}

class HotelSearchView extends GetView<HotelSearchController> {
  const HotelSearchView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.white,
            leading: InkWell(
              onTap: Get.back,
              child: Icon(
                Icons.arrow_back_ios,
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                size: 20.w,
              ),
            ),
            leadingWidth: 40.w,
            title: Container(
              height: 38.h,
              padding: EdgeInsets.symmetric(horizontal: 10.w),
              margin: EdgeInsets.only(right: 20.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20.w),
                  border: Border.all(
                      color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3478))),
              child: Row(
                children: [
                  Column(
                    children: [
                      Container(
                        padding: EdgeInsets.only(top: 4.h),
                        alignment: Alignment.centerLeft,
                        child: Text.rich(TextSpan(
                            text: '住 ',
                            style: StylesUtils.customTextStyle(
                                fontSize: 12.sp, color: ColorsUtils.color9999),
                            children: [
                              TextSpan(
                                  text: '11-25',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 12.sp, color: ColorsUtils.color3478))
                            ])),
                      ),
                      Container(
                        padding: EdgeInsets.only(top: 3.h),
                        alignment: Alignment.centerLeft,
                        child: Text.rich(TextSpan(
                            text: '离 ',
                            style: StylesUtils.customTextStyle(
                                fontSize: 12.sp, color: ColorsUtils.color9999),
                            children: [
                              TextSpan(
                                  text: '11-28',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 12.sp, color: ColorsUtils.color3478))
                            ])),
                      )
                    ],
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 5.w),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '北海',
                      style: StylesUtils.customTextStyle(
                          fontSize: 13.sp, color: ColorsUtils.color3478),
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    child: ToolsUtils.assetImageSvg('u1366.svg', width: 2.w, height: 15.h),
                  ),
                  Expanded(
                      child: Container(
                    padding: EdgeInsets.only(left: 5.w),
                    child: TextField(
                      controller: controller.textEditingController,
                      cursorWidth: 2.0,
                      cursorRadius: const Radius.circular(2),
                      cursorColor: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                      style: StylesUtils.customTextStyle(
                          fontSize: 13.sp, color: ColorsUtils.color3333),
                      decoration: InputDecoration(
                        prefixIcon: Icon(Icons.search_sharp, size: 25.sp),
                        prefixIconColor: Colors.black54,
                        prefixIconConstraints: BoxConstraints.expand(width: 35.w),
                        border: InputBorder.none,
                        focusedBorder: InputBorder.none,
                        hintText: '酒店地名',
                        contentPadding: EdgeInsets.symmetric(vertical: 12.h),
                        isCollapsed: true,
                        isDense: true,
                        hintStyle: StylesUtils.customTextStyle(
                            color: ColorsUtils.color3333, fontSize: 13.sp),
                        suffixIcon:
                            ToolsUtils.assetImageSvg('u1465.svg', width: 16.w, height: 16.h),
                        suffixIconConstraints: BoxConstraints.expand(width: 16.w, height: 16.h),
                      ),
                    ),
                  ))
                ],
              ),
            ),
            bottom: PreferredSize(
              preferredSize: Size.fromHeight(40.h),
              child: Row(
                  children: controller.tabs
                      .asMap()
                      .map((index, name) => MapEntry(
                          index,
                          Expanded(
                            child: Center(
                                child: TextButton(
                                    onPressed: () {
                                      if (index != controller.tabIndex.value) {
                                        controller.tabIndex.value = index;
                                      }
                                    },
                                    child: Text(
                                      name,
                                      style: activeTextStyle(index),
                                    ))),
                          )))
                      .values
                      .toList()),
            ),
          ),
          body: scrollRefreshConfig(context),
        ));
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      itemBuilder: (_, index) {
        var row = controller.pageList[index];
        return InkWell(onTap: () {
          Get.toNamed(RoutePath.hotelInfo, arguments: {'hotel': row });
        }, child: Container(
          margin: EdgeInsets.only(top: 20.h),
          padding: EdgeInsets.symmetric(vertical: 7.5.h, horizontal: 10.w),
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8.w)),
          child: Row(
            children: [
              Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(5.w),
                    child: CachedNetworkImage(
                      imageUrl: row.imgUrl,
                      width: 90.w,
                      height: 90.h,
                      fit: BoxFit.fill,
                    ),
                  ),
                  Positioned(
                      left: 0,
                      bottom: 0,
                      right: 0,
                      child: Container(
                        height: 20.h,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: ColorsUtils.rgba(0, 0, 0, 0.6),
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(5.w),
                                bottomRight: Radius.circular(5.w))),
                        child: Text(
                          row.area,
                          style: StylesUtils.customTextStyle(
                            fontSize: 12.sp,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ))
                ],
              ),
              Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 10.w),
                    child: Column(
                      children: [
                        Container(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            row.name,
                            style: StylesUtils.customTextStyle(
                                fontSize: 15.sp,
                                fontWeight: FontWeight.w700,
                                color: ColorsUtils.color3333),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Expanded(
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                row.address,
                                style: StylesUtils.customTextStyle(
                                    fontSize: 12.sp, color: ColorsUtils.color9999),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            )),
                        Container(
                            alignment: Alignment.centerLeft,
                            child: Text.rich(TextSpan(children: [
                              TextSpan(
                                  text: '￥',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 13.sp, color: ColorsUtils.colorD900)),
                              TextSpan(
                                  text: ' ${row.price} ',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.w700,
                                      color: ColorsUtils.colorD900)),
                              TextSpan(
                                  text: '起',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 12.sp, color: ColorsUtils.color9999))
                            ])))
                      ],
                    ),
                  ))
            ],
          ),
        ),);
      },
      itemCount: controller.pageList.length,
      itemExtent: 130.h,
      cacheExtent: 130.h,
    );
  }

  TextStyle activeTextStyle(int index) {
    if (controller.tabIndex.value == index) {
      return StylesUtils.customTextStyle(fontSize: 13.sp, color: ColorsUtils.color3478);
    }
    return StylesUtils.customTextStyle(fontSize: 13.sp, color: ColorsUtils.color3333);
  }
}
